import { catalog } from "@mall/api-services"
import { PageHeader } from "antd"
import * as React from "react"
import { useEffect, useState } from "react"
import { useParams } from "react-router-dom"
import { messageError } from "../../utils/reason"

import classes from "./edit-product.module.scss"
import ProductForm from "./product-form"

interface EditProductProps {

}

export default function EditProduct(props: EditProductProps) {

  const { productId = "" } = useParams()
  const [product, setProduct] = useState(new catalog.Product())
  const [loading, setLoading] = useState(false)

  useEffect(() => {
    catalog.ProductServiceV1.getProduct(productId)
      .then(setProduct)
      .catch(messageError)
  }, [productId])

  function onFinish(newProduct: catalog.Product) {
    setLoading(true)
    catalog.ProductServiceV1
      .updateProduct(newProduct)
      .catch(messageError)
      .finally(() => setLoading(false))
  }

  return (
    <div className={classes.editProduct}>
      <PageHeader title="编辑商品" ghost={false}/>
      <div className={classes.editProductContent}>
        <ProductForm loading={loading} product={product} onFinish={onFinish}/>
      </div>
    </div>
  )

}
